﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using System.ComponentModel;

using System.Net;

namespace gTray
{
    public delegate void FeedUpdatedHandler(Feed UpdatedFeed);
    public delegate void FeedErrorHandler(string message);

    public class gTrayService
    {
        private Feed _Feed;
        private Timer _Timer;
        private BackgroundWorker _Worker;
        private bool _IsParsing;
        private NetworkCredential _Credentials;
        private frmOptions _OptionForm;

        public event FeedUpdatedHandler FeedUpdated;
        public event FeedErrorHandler FeedError;

        /// <summary>
        /// Initializes a new instance of the <see cref="gTrayService"/> class.
        /// </summary>
        public gTrayService()
        {
            //Creates the timer that updates the Feed
            _Timer = new Timer();
            _Timer.Interval = TimeSpan.FromSeconds(SettingService.Instance.RecheckIntervalSeconds).TotalMilliseconds;
            _Timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
            _Timer.AutoReset = true;

            //Creates the background worker that puts the thread update onto a seperate thread.
            _Worker = new BackgroundWorker();
            _Worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
            _Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);

            //Boolean to stop the update if it is un-needed.
            _IsParsing = false;
        }

        /// <summary>
        /// Starts the timer.
        /// </summary>
        public void StartTimer()
        {
            _Timer.Start();
            Timer_Elapsed(_Timer, null);
        }

        /// <summary>
        /// Stops the timer.
        /// </summary>
        public void StopTimer()
        {
            _Timer.Stop();
        }

        void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                FeedParser.ParseGmailFeed(ref _Feed, _Credentials);
            }
            catch (Exception ex)
            {
                if (FeedError != null)
                    FeedError(ex.Message);
            }
        }

        void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_Feed.NewEntries.Count > 0)
            {
                if (this.FeedUpdated != null)
                    FeedUpdated(_Feed);
            }

            _IsParsing = false;
        }

        void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (_IsParsing == false)
            {
                _IsParsing = true;
                _Worker.RunWorkerAsync();
            }
        }

        /// <summary>
        /// Checks the feed now.
        /// </summary>
        public void ForceUpdateFeed()
        {
            StopTimer();
            _Feed = null;
            StartTimer();
        }

        public void ShowOptionDialog(System.Windows.Forms.IWin32Window owner)
        {
            StopTimer();

            if (_OptionForm != null)
            {
                if (_OptionForm.Visible == true)
                    _OptionForm.BringToFront();
            }
            else
            {
                _OptionForm = new frmOptions();
                _OptionForm.ShowDialog(owner);

                //Clean up the options form.
                _OptionForm.Dispose();
                _OptionForm = null;
            }

            StartTimer();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="owner">The owner.</param>
        /// <returns></returns>
        public bool Login(System.Windows.Forms.IWin32Window owner)
        {
            //Check the Internet Connection (to make sure it's at least up)
            if (!NetService.IsConnectedToInternet())
                return false;

            if (SettingService.Instance.DoAutoLogin == false)
            {
                frmLogin login = new frmLogin();
                _Credentials = login.ShowAndGetCredentials(owner);
                
                //Clear login form
                login.Dispose();
                login = null;

                if (_Credentials == null)
                    return false;
            }
            else
            {
                _Credentials = SettingService.Instance.GetAutoLoginCredential();

                if (_Credentials == null)
                {
                    //Means there is a problem loading the user's credentials (crypto error) 
                    //Unhandled currently
                }
            }


            return true;
        }

        /// <summary>
        /// Edits the login details.
        /// </summary>
        /// <param name="owner">The owner.</param>
        public void ShowEditLoginDialog(System.Windows.Forms.IWin32Window owner)
        {
            StopTimer();

            frmLogin editLogin = new frmLogin();
            NetworkCredential credential = editLogin.ShowAndEditCredentials(owner, _Credentials);
            
            //Clear login form
            editLogin.Dispose();
            editLogin = null;

            if (credential != null)
                _Credentials = credential;

            StartTimer();
        }
    }
}
